package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.MaxkeyService;
import org.maxkey.client.entity.UserInfo;
import org.maxkey.client.oauth.OAuthClient;
import org.maxkey.client.oauth.model.Token;
import org.maxkey.client.oauth.model.Verifier;
import org.maxkey.client.oauth.oauth.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SsoLoginController {

    @Autowired
    private MaxkeyService maxkeyService;
    @Autowired
    private ISysUserService userService;

    @GetMapping("/ssoLogin/getAuthorizationUrl")
    public String handleSsoLoginCallback() {
        OAuthService service = maxkeyService.generateService();
        Token EMPTY_TOKEN = null;
        String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
        return authorizationUrl;
    }

    @GetMapping("/ssoLogin/getToken/{code}")
    public String getAcessToken(@PathVariable String code){
        OAuthService service = maxkeyService.generateService();
        Token EMPTY_TOKEN = null;
        Verifier verifier = new Verifier(code);
        Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
        String access_token = accessToken.getAccess_token();
        OAuthClient restClient = new OAuthClient("http://sso.maxkey.top/sign/api/oauth/v20/me",access_token);
        UserInfo userInfo=restClient.getUserInfo(accessToken.getAccess_token());
        //换令牌
        String username = userInfo.getUsername();
        SysUser sysUser = userService.selectUserByUserName(username);
        if(sysUser!=null){
            return  maxkeyService.Ssologin(username, sysUser.getPassword());
        }else{
            return  null;
        }

    }
}
